import { getDictionaryEntryList } from '@/api/dictionary'
import { cloneDeep } from 'lodash-es'
const useDictionaryEntry = () => {
  // 获取当前查询条件下的数据
  const getDictionaryEntryData = async (data) => {
    const result: any = {}
    result.label = data.label
    result.status = data.status
    result.type = data.type
    const res: any = await getDictionaryEntryList(result, { config: { showLoading: false, mockEnable: true } })
    if (res.data && res.data.length > 0) {
      return dataToTree(res.data)
    } else {
      return []
    }
  }
  const dataToTree = (data) => {
    const dataArr = cloneDeep(data)
    const parents = dataArr.filter(function (item: any) {
      return item.pid === 0
    })
    const children = dataArr.filter(function (item: any) {
      return item.pid !== 0
    })
    // 递归处理动态路由层级
    convert(parents, children)
    return parents
  }
  const convert = (parents: any, children: any) => {
    parents.forEach(function (item: any) {
      item.children = []
      children.forEach(function (current: any, index: any) {
        if (current.pid === item.id) {
          const temp = children.filter(function (v: any, idx: any) {
            return idx !== index
          }) // 删除已匹配项，这里未使用JSON.parse(JSON.stringify(children))是因为路由的component已经是函数形式，再格式化后，模块导入功能丢失，会导致找不到模块
          item.children.push(current)
          convert([current], temp) // 递归
        }
      })
    })
  }
  return {
    getDictionaryEntryData
  }
}
export default useDictionaryEntry
